// 本地存储工具类

import type { FilterState } from '@/types';

const STORAGE_KEYS = {
  FILTER_STATE: 'env_manager_filter_state',
  ACTIVE_ENVIRONMENTS: 'env_manager_active_environments',
};

export class StorageManager {
  private static instance: StorageManager;

  private constructor() {}

  public static getInstance(): StorageManager {
    if (!StorageManager.instance) {
      StorageManager.instance = new StorageManager();
    }
    return StorageManager.instance;
  }

  // 保存筛选状态
  public saveFilterState(filterState: FilterState): void {
    try {
      localStorage.setItem(STORAGE_KEYS.FILTER_STATE, JSON.stringify(filterState));
    } catch (error) {
      console.error('保存筛选状态失败:', error);
    }
  }

  // 获取筛选状态
  public getFilterState(): FilterState {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.FILTER_STATE);
      if (data) {
        return JSON.parse(data);
      }
    } catch (error) {
      console.error('获取筛选状态失败:', error);
    }
    
    // 返回默认状态
    return {
      searchKeyword: '',
      selectedGroupIds: [],
    };
  }

  // 保存活跃环境状态
  public saveActiveEnvironments(activeEnvs: Record<string, string[]>): void {
    try {
      localStorage.setItem(STORAGE_KEYS.ACTIVE_ENVIRONMENTS, JSON.stringify(activeEnvs));
    } catch (error) {
      console.error('保存活跃环境状态失败:', error);
    }
  }

  // 获取活跃环境状态
  public getActiveEnvironments(): Record<string, string[]> {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.ACTIVE_ENVIRONMENTS);
      if (data) {
        return JSON.parse(data);
      }
    } catch (error) {
      console.error('获取活跃环境状态失败:', error);
    }
    
    return {};
  }

  // 清除所有存储数据
  public clearAll(): void {
    try {
      localStorage.removeItem(STORAGE_KEYS.FILTER_STATE);
      localStorage.removeItem(STORAGE_KEYS.ACTIVE_ENVIRONMENTS);
    } catch (error) {
      console.error('清除存储数据失败:', error);
    }
  }
}

// 导出单例实例
export const storageManager = StorageManager.getInstance();
